<template>
  <el-card class="tree-card">
    <TreeTools :is-root="true" :tree-node="company" @addDepts="addDepts" />
    <hr>
    <el-tree :data="departs" :props="{label:'name',children: 'children'}">
      <TreeTools slot-scope="{data}" :tree-node="data" @delDepts="getDepartments" @addDepts="addDepts" @editDepts="editDepts" />
    </el-tree>
    <AddDept ref="addDept" :show-dialog.sync="showDialog" :node="node" @addDepts="getDepartments" />
  </el-card>

</template>

<script>
import { transListToTreeData } from '@/utils/index'
import { getDepartments } from '@/api/departments'
import TreeTools from './components/tree-tools'
import AddDept from './components/add-dept'
export default {
  components: {
    // 注册组件
    TreeTools,
    AddDept

  },
  data() {
    return {
      departs: [],
      company: {
        name: '江苏传智播客教育科技股份有限公司',
        manager: '负责人',
        id: ''
      },
      showDialog: false,
      node: {}

    }
  },
  async created() {
    // 获取一开始的页面数据
    this.getDepartments()
    console.log(this.departs)
  },
  methods: {
    // 刷新页面数据
    async getDepartments() {
      const res = await getDepartments()
      this.departs = transListToTreeData(res.depts, '')
    },
    addDepts(treeNode) {
      console.log(treeNode)
      // 1. 控制弹窗
      this.showDialog = true
      // 2. 将获取的 treeNode 传给弹窗
      this.node = treeNode
    },
    // 编辑
    async editDepts(treeNode) {
      this.showDialog = true
      // 因为是编辑, 除了弹窗以外, 还需要执行子组件获取数据方法
      // 来实现数据回显
      await this.$refs.addDept.getDepartDetail(treeNode.id)
      this.node = treeNode
    }

  }
}
</script>

<style lang="scss" scoped>
.tree-card {
  padding: 30px  140px;
  font-size:14px;

}
</style>
